package com.gykfbxxh.imovie.base;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.app.utils.util.SystemBarTintManager;
import com.app.utils.util.ToastUtils;
import com.baidu.mobstat.StatService;
import com.gykfbxxh.imovie.R;
import com.gykfbxxh.imovie.config.AppConfigTools;
import com.gykfbxxh.imovie.listener.BackGestureListener;
import com.gykfbxxh.imovie.listener.HttpListener;
import com.gykfbxxh.imovie.manager.AppManager;
import com.gykfbxxh.imovie.utils.HttpUtils;
import com.umeng.analytics.MobclickAgent;

import java.lang.reflect.Type;
import java.util.Map;

/**
 * 所有Activity的基类
 * 所有子类必须设置 mPageName 变量(便于清除网络请求)
 * Created by xuxinghai
 * On 2017/8/17
 */
public class BaseActivity extends PermissionRequestActivity {

	protected String mPageName = "BaseActivity";//页面标识(继承的子类一律用此变量标识页面)

	//通用的识别码
	public final static int REQUESTCODE_1 = 1;//通用的请求码
	public final static String PARAMETER1 = "parameter1";//通用的参数1
	public final static String PARAMETER2 = "parameter2";//通用的参数1

	protected boolean request_state;//网络请求的请求状态

	//页面逻辑
	protected Activity mActivity;//当前activity的引用
	protected GestureDetector mGestureDetector;//左滑手势
	protected boolean pageConfigNotify;//默认不允许改变通知栏的颜色
	protected boolean isInit = true;//是否初始化页面
	protected boolean isSlideBack = true;//是否允许左滑动返回,默认左滑动结束页面
	protected long lastClickTime = 0;//最后点击返回的时间

//	private int mScreenLight = -1;//当前屏幕亮度
    private ViewGroup mBaseContentView;//父布局


	@SuppressLint("NewApi")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		//添加到管理栈
		AppManager.getAppManager().addActivity(this);
		//设置竖屏
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		//获取父布局
		if(isInit){
			mBaseContentView = (ViewGroup) getLayoutInflater().inflate(R.layout.activity_base, null);
			setContentView(mBaseContentView);
		}
		mActivity = this;

//		//添加左滑动结束
		if(isSlideBack && mGestureDetector == null){
			mGestureDetector = new GestureDetector(getApplicationContext(), new BackGestureListener(this));
//			SwipeBackLayout layout = (SwipeBackLayout) LayoutInflater.from(this).inflate(
//					R.layout.view_swipeback_layout, null);
//			layout.attachToActivity(this);
		}
		//设置页面样式
		setStylerBar(R.color.app_theme);
	}

	@Override
	public boolean dispatchTouchEvent(MotionEvent ev) {
		if(mGestureDetector != null && isSlideBack){
			return mGestureDetector.onTouchEvent(ev) || super.dispatchTouchEvent(ev);
		}
		return super.dispatchTouchEvent(ev);
	}

	/****************** 以下是被继承的方法  ***************/
	/*
	 * 返回
	 */
    public void doBack(View view) {
		long currentTime = System.currentTimeMillis();
		//如果连续点击的时间小于 MIN_CLICK_DELAY_TIME  则本次点击不起效
		if (currentTime - lastClickTime > 500) {
			lastClickTime = currentTime;
			onBackPressed();
		}
	}

	/**
	 * 设置页面标题,以及字体颜色
	 * @param title
	 */
	protected void setTitle(String title){
		if(TextUtils.isEmpty(title)){
			return;
		}
		TextView titleView = (TextView) findViewById(R.id.page_head_title);
		if(titleView != null){
			titleView.setText(title);
			titleView.setVisibility(View.VISIBLE);
		}

	}


	/**
	 * 设置title右边图标
	 */
	protected ImageView setTitleRightImage(int resId){
		ImageView pageHeadFunction = (ImageView)findViewById(R.id.page_head_function);
		if(pageHeadFunction != null){
			pageHeadFunction.setVisibility(View.VISIBLE);
			pageHeadFunction.setImageResource(resId);
		}
		return pageHeadFunction;
	}

	/**
	 * 设置title右边的文字
	 */
	protected TextView setTitleRightText(String text){
		TextView pageRightText = (TextView)findViewById(R.id.page_head_function_text);
		if(pageRightText != null){
			pageRightText.setVisibility(View.VISIBLE);
			pageRightText.setText(text);
		}
		return pageRightText;
	}


	/**
	 * title栏是否显示
	 * @param isShow
     */
	protected void setTitleShow(boolean isShow){
		RelativeLayout appTitle = (RelativeLayout)findViewById(R.id.rl_apptitle);
		if(appTitle != null){
			appTitle.setVisibility(isShow ? View.VISIBLE : View.GONE);
		}
	}

	/**
	 * 设置头部title栏背景颜色
	 * @param resId
	 */
	protected void setTitleBgColor(int resId){
		RelativeLayout appTitle = (RelativeLayout)findViewById(R.id.rl_apptitle);
		if(appTitle != null){
			appTitle.setBackgroundColor(getResources().getColor(resId));
		}

	}



    /**
     * 添加子布局
     * @param resourceId
     */
	protected void addContentView(int resourceId){
        View view = this.getLayoutInflater().inflate(resourceId,null);
		if(mBaseContentView != null && view != null){
			mBaseContentView.addView(view);
        }else{
			ToastUtils.showText(getString(R.string.exception_page_back));
            onBackPressed();
        }
    }

	/**
	 * 添加子布局
	 * @param view
	 */
	protected void addContentView(View view){
		if(mBaseContentView != null && view != null){
			mBaseContentView.addView(view);
		}else{
			ToastUtils.showText(getString(R.string.exception_page_back));
			onBackPressed();
		}
	}

	/**
	 * 改变背景色
	 * @param resId
	 */
	protected void changeBaseActivityBg(int resId){
		if(mBaseContentView != null){
			mBaseContentView.setBackgroundResource(resId);
		}
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
	}


	/**
	 * 发送一个post网络请求-----DataBean.getData是可能为空的
	 * @param url
	 * @param type
	 * @param parms
	 * @param httpListener
     */
	protected void addPostRequest(@NonNull String url, @NonNull Type type, Map<String, String> parms, @NonNull HttpListener<?> httpListener) {

		HttpUtils.addPostRequest(url, type, mPageName, parms,httpListener);
	}

	/**
	 * 发送一个post网络请求-----DataBean.getData是可能为空的
	 * @param url
	 * @param type
	 * @param parms
	 * @param httpListener
	 */
	protected void addPostCacheRequest(@NonNull String url, @NonNull Type type, Map<String, String> parms, @NonNull HttpListener<?> httpListener) {

		HttpUtils.addPostCacheRequest(url, type, mPageName, parms,httpListener);
	}


	/**
	 * 发送一个get网络请求
	 * @param url 请求地址 不为空,否则执行失败回调
	 * @param type
	 * @param httpListener
	 */
	protected void addGetRequest(@NonNull String url,@NonNull Type type, @NonNull HttpListener<?> httpListener){

		HttpUtils.addGetRequest(url, type, mPageName, httpListener);;
	}


	/****************** 被继承的方法  end **************/

	/******************所有重写的方法  end **************/

	@Override
	public void startActivity(Intent intent) {
		super.startActivity(intent);
		overridePendingTransition(R.anim.base_slide_right_in, R.anim.base_slide_remain);

	}
	@Override
	public void startActivityForResult(Intent intent, int requestCode) {
		super.startActivityForResult(intent, requestCode);
        overridePendingTransition(R.anim.base_slide_right_in, R.anim.base_slide_remain);
	}

	@Override
	public void onBackPressed() {
		AppManager.getAppManager().finishActivity();
		overridePendingTransition(0, R.anim.base_slide_right_out);
	}

	@Override
	protected void onResume() {
		super.onResume();

		// 百度统计
		StatService.onResume(this);
		// 友盟统计
		MobclickAgent.onResume(this);

//		//设置屏幕亮度
//		setScreenLight();
	}

	@Override
	protected void onPause() {
		super.onPause();
//		 百度统计
		StatService.onPause(this);
		// 友盟统计
		MobclickAgent.onPause(this);
//		//拉黑 点赞 关注 举报 操作存储
//		InteractiveUtils.getInstance().saveLaudList();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		//当页面destroy后,取消网络请求
		HttpUtils.cancelAllRequests(mPageName);
	}

	/******************所有重写的方法  end **************/

	/******************私有方法  start **************/

	/**
	 * 设置通知栏页面样式
	 */
	protected void setStylerBar(int resId){

		if (AppConfigTools.isSetNotify && pageConfigNotify) {
			setTranslucentStatus(true);
			SystemBarTintManager tintManager = new SystemBarTintManager(this);
			tintManager.setStatusBarTintEnabled(true);
			tintManager.setStatusBarTintResource(resId);// 通知栏所需颜色
		}

	}

	@TargetApi(19)
	private void setTranslucentStatus(boolean on) {
		Window win = getWindow();
		WindowManager.LayoutParams winParams = win.getAttributes();
		final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
		if (on) {
			winParams.flags |= bits;
		} else {
			winParams.flags &= ~bits;
		}
		win.setAttributes(winParams);
	}

	/******************私有方法  end **************/


}
